package com.jarveis.frame.task;

import java.util.ArrayList;

import org.apache.log4j.Logger;

/**
 * 任务监视器
 * 
 * @author liuguojun
 */
public class TaskMonitor extends Thread {

	private static final Logger logger = Logger.getLogger(TaskMonitor.class);
	
	private int allowIdleSecond = 5; // 允许空闲秒数
	private int refreshMS = 100; // 刷新时间
	private ArrayList<TaskThread> taskThreads; // 监视的线程集
	private TaskPool taskPool;

	public TaskMonitor(TaskPool taskPool) {
		this.taskPool = taskPool;
		allowIdleSecond = allowIdleSecond * (1000 / refreshMS);
		taskThreads = new ArrayList<TaskThread>(taskPool.getMaxSize());
	}

	/**
	 * 添加监视的工作
	 * 
	 * @param taskThread
	 */
	void push(TaskThread taskThread) {
		taskThread.setIdleSecond(0);
		int i = taskThreads.indexOf(taskThread);
		if (i >= 0) {
			taskThreads.set(i, taskThread);
		} else {
			taskThreads.add(taskThread);
		}
	}

	/**
	 * 删除空闲时间较长的线程
	 * 
	 * @param taskThread
	 */
	void remove(TaskThread taskThread) {
		if (taskThreads.size() > taskPool.getMinSize()) {
			taskThread.notifyStop();
			taskThreads.remove(taskThread);
			taskPool.removeIdle(taskThread);
			taskPool.remove(taskThread);
		}
	}

	public void run() {
		while (true) {
			if (taskThreads.size() > 5) {
				for (int i = taskThreads.size() - 1; i >= 0; i--) {
					TaskThread taskThread = taskThreads.get(i);
					if (taskThread.getWorkState() == 0) {
						// 当线程处于空闲时
						taskPool.pushIdle(taskThread);
						// 验证是否超过系统定义的空闲时间
						int idleSecond = taskThread.getIdleSecond();
						if (idleSecond >= allowIdleSecond) {
							remove(taskThread);
						}
						idleSecond++;
						taskThread.setIdleSecond(idleSecond);
					}
				}
			}
			try {
				Thread.sleep(refreshMS);
			} catch (InterruptedException ex) {
				logger.error(ex.getMessage(), ex);
			}
		}
	}
}
